package com.woniuxy.orderServer.util;

import cn.hutool.json.JSONUtil;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.woniuxy.orderServer.dto.alipay.PayInfoDto;
import com.woniuxy.orderServer.param.alipay.PagePayParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import static org.bouncycastle.asn1.x500.style.RFC4519Style.cn;

/**
 * alipay工具类
 */
@Component
public class AlipayUtil {
    @Autowired
    private AlipayClient alipayClient;

    /**
     * 网页支付方法 参数:封装支付参数，需要包含订单号、支付金额、支付说明、详细描述（可选）、同步回调地址、异步回调地址
     */
    public String pagePay(PagePayParam payParam) throws Exception {
        // 实例化网页支付请求对象
        AlipayTradePagePayRequest alipayTradePagePayRequest = new AlipayTradePagePayRequest();
        // 设置参数
        String content = "{\"timeout_express\":\"" + payParam.getPayTimeBorder() + "m\",\"out_trade_no\":\"" + payParam.getOrderId() + "\"," + "\"total_amount\":\"" + payParam.getMoney()
                + "\"," + "\"subject\":\"" + payParam.getSubject() + "\"," + "\"body\":\"" + payParam.getBody() + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}";
        alipayTradePagePayRequest.setBizContent(content);
        //设置同步回调和异步回调
        alipayTradePagePayRequest.setNotifyUrl(payParam.getNotifyUrl());
        alipayTradePagePayRequest.setReturnUrl(payParam.getReturnUrl());
        //执行网页支付请求
        AlipayTradePagePayResponse execute = alipayClient.pageExecute(alipayTradePagePayRequest);
        //判断支付宝响应结果
        if (execute.isSuccess()) {
            //返回支付宝响应的支付表单html内容
            return execute.getBody();
        }
        //不成功
        throw new Exception("支付失败");
    }

    public PayInfoDto queryPayState(String orderNum) throws Exception {
        //设置请求参数
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
//请二选一设置
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + orderNum + "\"}");
//请求
        String result = alipayClient.execute(alipayRequest).getBody();
//输出
        String orderInfo = JSONUtil.parseObj(result).get("alipay_trade_query_response").toString();
        String payCode = JSONUtil.parseObj(orderInfo).get("code").toString();
        if ("10000".equals(payCode)) {
            String payDate = JSONUtil.parseObj(orderInfo).get("send_pay_date").toString();
            String payState = JSONUtil.parseObj(orderInfo).get("trade_status").toString();
            PayInfoDto dto = new PayInfoDto(payDate, payState);
            return dto;
        } else {
            PayInfoDto dto = new PayInfoDto(null, "TRADE_FAIL");
            return dto;
        }
    }

    public HashMap<String, String> payNotify(HttpServletRequest req){
        HashMap<String, String> params = new HashMap<>();
        //获取支付宝请求的所有参数
        Map<String, String[]> reqParameterMap = req.getParameterMap();
        //通过迭代，获取所有
        for (Iterator<String> iterator = reqParameterMap.keySet().iterator(); iterator.hasNext();){
            String name = iterator.next();
            String[] values = (String[]) reqParameterMap.get(name);//String[],因为value可能不只一个
            String valueStr="";
            for (int i = 0; i < values.length; i++) {
                valueStr=(i==values.length-1)?valueStr+values[i]:valueStr+values[i]+",";
            }
            params.put(name,valueStr);
        }
        return params;
    }
}
